package com.poobo.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.poobo.aop.SystemCtrLo4jAop;
import com.poobo.entity.TbResources;
import com.poobo.service.IEqGamesInfoService;
import com.poobo.service.IResourcesConfigService;
import com.poobo.service.IResourcesService;
import com.poobo.util.date.DateUtil;
import com.poobo.util.pager.Page;
import com.poobo.util.property.PropertyUtil;
import com.poobo.util.str.StrUtil;


@Controller
@RequestMapping("resources")
public class ResourcesCtr {
	
	@Autowired
	private IResourcesService resourcesService;
	@Autowired
	private IEqGamesInfoService eqGamesInfoService;
	@Autowired
	private IResourcesConfigService resourcesConfigService;
	/**
	 * 资源列表
	 * @param request
	 * @param resources
	 * @param page
	 * @return
	 */
	@RequestMapping("toResourcesList")
	public String resourcesList( HttpServletRequest request,TbResources resources,Page page ){
		if( resources.getName() != null ){
			request.setAttribute("name", resources.getName());
		}if( resources.getName() != null ){
			request.setAttribute("name", resources.getName());
		}if( resources.getType() != null ){
			if(resources.getType() == 0 ){
				request.setAttribute("type", "游戏");
			}else if(resources.getType() == 1 ){
				request.setAttribute("type", "视频");
			}else if(resources.getType() == 2 ){
				request.setAttribute("type", "图片");
			}else{
				request.setAttribute("type", "");
			}
		}if( resources.getLastName() != null ){
			request.setAttribute("lastName", resources.getLastName());
		}
		page = resourcesService.queryResourcesPage(resources, page);
		request.setAttribute("resourcesList", page.getPageList());
		request.setAttribute("pageNo", page.getPageNo());
		request.setAttribute("pageNum", page.getPageNum());
		request.setAttribute("pageSize", page.getPageSize());
		return "resources/resources_list";
	}
	/**
	 * 根据Id删除资源
	 * @param request
	 * @return
	 */
	@RequestMapping("deleteById")
	@SystemCtrLo4jAop(description="删除单个资源")
	public String deleteEquipmetById( HttpServletRequest request , TbResources resources){
		Integer id = Integer.parseInt(request.getParameter("resourcesId"));
		resources = resourcesService.queryResourcesById(id);
		if( !"".equals(resources.getPath()) && resources.getPath() != null ){
			String fileName = resources.getPath().substring(resources.getPath().lastIndexOf("/") + 1);
			File file = new File(PropertyUtil.configProperty.getProperty("resource_disk_base_path") + File.separator + PropertyUtil.configProperty.getProperty("resource_resources") + File.separator + fileName);
			if(file.exists()){
				file.delete();
			}
		}
		resourcesService.deleteResourcesById(id);
		//外键删除
		eqGamesInfoService.deleteEqGamesInfoByResourcesId(id);
		resourcesConfigService.deleteResourcesConfigByResourcesId(id);
		return "redirect:/resources/toResourcesList.html";
	}
	@RequestMapping("deleteByIds")
	@SystemCtrLo4jAop(description="批量删除资源")
	public String deleteEquipmetByIds( HttpServletRequest request , TbResources resources){
		String ids = request.getParameter("ids");
		String[] idss = ids.split(",");
		Integer id = null;
		for (String idStr : idss) {
			id = Integer.parseInt(idStr);
			resources = resourcesService.queryResourcesById(id);
			if( !"".equals(resources.getPath()) && resources.getPath() != null ){
				String fileName = resources.getPath().substring(resources.getPath().lastIndexOf("/") + 1);
				File file = new File(PropertyUtil.configProperty.getProperty("resource_disk_base_path") + File.separator + PropertyUtil.configProperty.getProperty("resource_resources") + File.separator + fileName);
				if(file.exists()){
					file.delete();
				}
			}
			resourcesService.deleteResourcesById(id);
			eqGamesInfoService.deleteEqGamesInfoByResourcesId(id);
			resourcesConfigService.deleteResourcesConfigByResourcesId(id);
		}
		return "redirect:/resources/toResourcesList.html";
	}
	/**
	 * 跳转新增页面
	 * @param resources
	 * @param request
	 * @return
	 */
	@RequestMapping("toResourcesDetailPage")
	public String toResourcesDetailPage( TbResources resources, HttpServletRequest request ){
		return "resources/save_resources";
	}
	/**
	 * 跳转编辑页面
	 * @param resources
	 * @param request
	 * @return
	 */
	@RequestMapping("toResourcesDetail")
	public String toResourcesDetail( TbResources resources, HttpServletRequest request ){
		resources = resourcesService.queryResourcesById( Integer.parseInt(request.getParameter("resourcesId")));
		request.setAttribute("resources",resources);
		return "resources/edit_resources";
	}
	/**
	 * 保存资源
	 * @param file
	 * @param resources
	 * @param request
	 * @return
	 */
	@RequestMapping("saveResources")
	@SystemCtrLo4jAop(description="新增资源")
	public String saveResources( @RequestParam(value="file",required=false) MultipartFile file ,
			TbResources resources, HttpServletRequest request ){
		try {
			File res = new File(PropertyUtil.configProperty.getProperty("resource_disk_base_path") );
			// 如果文件夹不存在则创建 
			if (!res.exists()) {
				res.mkdirs();
			}
			File saveUrl = new File(PropertyUtil.configProperty.getProperty("resource_disk_base_path") + File.separator + PropertyUtil.configProperty.getProperty("resource_resources"));
			// 如果文件夹不存在则创建 
			if (!saveUrl.exists() && !saveUrl.isDirectory()) {
				saveUrl.mkdirs();
			}
			String fileName = file.getOriginalFilename();
			file.transferTo( new File(saveUrl + File.separator + fileName));
			String[] strs = fileName.split("\\.");
			if( StrUtil.isEmpty(resources.getName()) || resources.getName() == null || resources.getName() == "" ){
				resources.setName(strs[0]);
			}
			String httpPath = PropertyUtil.configProperty.getProperty("resource_http_base_path") + "/" + PropertyUtil.configProperty.getProperty("resource_resources");
			String newFileName = DateUtil.getNowTimeStr("yyyyMMddHHmmssSSS") + StrUtil.getRandomNum(10000);
			int index = fileName.lastIndexOf(".");
			String suffix = fileName.substring(index);
			File f=new File(saveUrl + File.separator + fileName);   
		    String c=f.getParent();   
		    File reName=new File(c+File.separator + newFileName + suffix);   
		    f.renameTo(reName); 
			resources.setLastName(suffix);
			resources.setPath(httpPath + "/" + newFileName + suffix);
			resourcesService.saveResources(resources);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/resources/toResourcesList.html";
	}
	/**
	 * 编辑资源
	 * @param file
	 * @param resources
	 * @param request
	 * @return
	 */
	@RequestMapping("editResources")
	@SystemCtrLo4jAop(description="编辑资源")
	public String editResources( @RequestParam(value="file",required=false) MultipartFile file ,
			TbResources resources, HttpServletRequest request ){
		try {
			File saveUrl = new File(PropertyUtil.configProperty.getProperty("resource_disk_base_path") + File.separator + PropertyUtil.configProperty.getProperty("resource_resources"));
			// 如果文件夹不存在则创建 
			if (!saveUrl.exists() && !saveUrl.isDirectory()) {
				saveUrl.mkdirs();
			}
			if( !file.isEmpty() ){
				if( !"".equals(resources.getPath()) && resources.getPath() != null ){
					String oldfileName = resources.getPath().substring(resources.getPath().lastIndexOf("/") + 1);
					File oldfile = new File(PropertyUtil.configProperty.getProperty("resource_disk_base_path") + File.separator + PropertyUtil.configProperty.getProperty("resource_resources") + File.separator + oldfileName);
					if(oldfile.exists()){
						oldfile.delete();
					}
				}
				String fileName = file.getOriginalFilename();
				file.transferTo( new File(saveUrl + File.separator + fileName));
				String[] strs = fileName.split("\\.");
				if( StrUtil.isEmpty(resources.getName()) || resources.getName() == null || resources.getName() == "" ){
					resources.setName(strs[0]);
				}
				String httpPath = PropertyUtil.configProperty.getProperty("resource_http_base_path") + "/" + PropertyUtil.configProperty.getProperty("resource_resources");
				String newFileName = DateUtil.getNowTimeStr("yyyyMMddHHmmssSSS") + StrUtil.getRandomNum(10000);
				int index = fileName.lastIndexOf(".");
				String suffix = fileName.substring(index);
				File f=new File(saveUrl + File.separator + fileName);   
			    String c=f.getParent();   
			    File reName=new File(c+File.separator + newFileName + suffix);   
			    f.renameTo(reName); 
				resources.setLastName(suffix);
				resources.setPath(httpPath + "/" + newFileName + suffix);
			}
			resourcesService.saveResources(resources);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/resources/toResourcesList.html";
	}
}
